package com.songleibing.project.pipeline.impl;

import com.songleibing.project.pipeline.Handler;
import com.songleibing.project.pipeline.HandlerChain;
import com.songleibing.project.pipeline.HandlerContext;

public class BaseHandlerChain implements HandlerChain {
    private Handler[] handlers = new Handler[0];

    private Integer currentHandlerIndex = 0;

    public void addHandler(Handler handler) {
        if (handler == null) {
            throw new IllegalArgumentException();
        }
        Handler[] newHandlers = new Handler[handlers.length + 1];
        System.arraycopy(handlers, 0, newHandlers, 0, handlers.length);
        newHandlers[handlers.length] = handler;
        handlers = newHandlers;
    }

    @Override
    public void handle(HandlerContext context) throws Exception {
        if (currentHandlerIndex < handlers.length) {
            Handler handler = handlers[currentHandlerIndex++];
            handler.handle(this, context);
        }
    }
}
